package com.kgc.controller;

import com.jcraft.jsch.SftpException;
import com.kgc.annotation.CheckPermission;
import com.kgc.entity.Product;
import com.kgc.service.ProductService;
import com.kgc.util.ResultAjax;
import com.kgc.util.SftpUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author :qinya
 * @PackageName:com.kgc.controller
 * @ClassName: ProductController
 * @Description: TODO
 * @date : 2025/5/19,21:41
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private RedisTemplate redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);

    @GetMapping("/page")
    @CheckPermission("1")
    public ResultAjax queryByPage(@RequestParam Map<String, String> params) {
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(params.get("searchProductName"))) {
            map.put("searchProductName", params.get("searchProductName"));
        }
        if (!StringUtils.isEmpty(params.get("searchCategoryId"))) {
            map.put("searchCategoryId", params.get("searchCategoryId"));
        }
        map.put("pageNum", Integer.parseInt(params.get("pageNum")));
        map.put("pageSize", Integer.parseInt(params.get("pageSize")));
        return ResultAjax.success().add("pageInfo", productService.selectByPage(map));
    }

    @PostMapping("/add")
    @CheckPermission("1")
    public ResultAjax addProduct(Product product, @RequestParam("pic") MultipartFile pic) {
        product.setCreateDate(new Date());
        String newFileName = UUID.randomUUID().toString() + '.' + FilenameUtils.getExtension(pic.getOriginalFilename());
//        String newFileName = "777"+'.'+ FilenameUtils.getExtension(pic.getOriginalFilename());
        SftpUtil sftp = new SftpUtil("qinya", "123123", "192.168.176.240", 22);
        sftp.login();
        try {
            InputStream is = pic.getInputStream();
            sftp.upload("/home/qinya/images", newFileName, is);
            product.setFileName(newFileName);
        } catch (SftpException | IOException e) {
            e.printStackTrace();
        } finally {
            sftp.logout();
        }
        return ResultAjax.success().add("addStatus", productService.addProduct(product));
    }

    @PostMapping("/edit")
    @CheckPermission("1")
    public ResultAjax editProduct(Product product, @RequestParam(value = "pic", required = false) MultipartFile pic) {
        if (!StringUtils.isEmpty(product.getFileName()) && pic == null) {
            return ResultAjax.success().add("editStatus", productService.editProduct(product));
        }
        String oldFileName = product.getFileName();

        String newFileName = UUID.randomUUID().toString() + '.' + FilenameUtils.getExtension(pic.getOriginalFilename());
        SftpUtil sftp = new SftpUtil("qinya", "123123", "192.168.176.240", 22);
        sftp.login();
        try {
            //删除原来的图片
            sftp.delete("/home/qinya/images",oldFileName);
            //输入流存新的图片
            InputStream is = pic.getInputStream();
            sftp.upload("/home/qinya/images", newFileName, is);
            product.setFileName(newFileName);
        } catch (SftpException | IOException e) {
            e.printStackTrace();
        } finally {
            sftp.logout();
        }
        return ResultAjax.success().add("editStatus", productService.editProduct(product));
    }

    @GetMapping("/del/{id}")
    @CheckPermission("1")
    public ResultAjax delProduct(@PathVariable("id") String id) throws SftpException {
        String fileName = productService.selectById(id).getFileName();
        boolean temp = productService.delProduct(id);
        if(temp){
            SftpUtil sftp = new SftpUtil("qinya", "123123", "192.168.176.240", 22);
            sftp.login();
            sftp.delete("/home/qinya/images",fileName);
            sftp.logout();
        }
        return ResultAjax.success().add("delStatus", temp);
    }

    @CheckPermission("0")
    @RequestMapping("/getProductById")
    public ResultAjax getProductById(@RequestBody HashMap<String, String> map) {
        String id = map.get("id");
        return ResultAjax.success().add("product", productService.selectById(id));
    }

    @CheckPermission("0")
    @RequestMapping("/getCategoryByProductId")
    public ResultAjax getCategoryByProductId(@RequestBody HashMap<String, String> map) {
        String productId = map.get("id");
        Product product = productService.selectById(productId);
        return ResultAjax.success().add("categoryList", productService.selectCategoryByProduct(product));

    }

    @GetMapping("/find/{id}")
    public ResultAjax findProduct(@PathVariable("id") String id) {
        return ResultAjax.success().add("product", productService.selectById(id));
    }

    @GetMapping("/check")
    @CheckPermission({"1", "0"})
    public ResultAjax checkProductStock(int preOut, String productId) {
        return ResultAjax.success().add("checkStatus", productService.checkStock(preOut, productId));
    }

    @RequestMapping("/addCollect")
    @CheckPermission({"1", "0"})
    public ResultAjax addCollect(@RequestBody HashMap<String, String> map) {
        String productId = map.get("productId");

        String userId = map.get("userId");
        try {
            // 获取 ListOperations 对象
            ListOperations<String, Product> listOperations = redisTemplate.opsForList();
            List<Product> collects = listOperations.range(userId, 0, -1);

            // 检查是否已经收藏了该商品
            if (collects != null) {
                for (Product collect : collects) {
                    if (productId.equals(collect.getId())) {
                        return ResultAjax.error().add("result", "已经收藏了该商品");
                    }
                }
            }

            Product product = productService.selectById(productId);
            // 将productId添加到userId对应的列表中，实现先进先出
            listOperations.leftPush(userId, product);

            // 限制列表长度为6，超出部分自动删除
            listOperations.trim(userId, 0, 5);

            return ResultAjax.success().add("result", "添加收藏成功");
        } catch (Exception e) {
            return ResultAjax.error().add("result", e.getMessage());
        }
    }


    @RequestMapping("/getCollects")
    @CheckPermission({"1", "0"})
    public ResultAjax getCollects(@RequestBody HashMap<String, String> map) {
        String userId = map.get("id");
        try {
            // 获取 ListOperations 对象
            ListOperations<String, Product> listOperations = redisTemplate.opsForList();
            // 获取用户的所有收藏
            List<Product> collects = listOperations.range(userId, 0, -1);
            if (collects != null && !collects.isEmpty()) {
                return ResultAjax.success().add("result", collects);
            }
            return ResultAjax.success().add("result", "无收藏");
        } catch (Exception e) {
            return ResultAjax.error().add("result", e.getMessage());
        }
    }

    @RequestMapping("/clearAllCollects")
    @CheckPermission({"1", "0"})
    public ResultAjax clearAllCollects(@RequestBody HashMap<String, String> map) {
        String userId = map.get("id");
        try {
            // 删除指定用户的所有收藏
            redisTemplate.delete(userId);
            return ResultAjax.success().add("result", "收藏夹已清空");
        } catch (Exception e) {
            return ResultAjax.error().add("result", e.getMessage());
        }
    }


    @RequestMapping("/deleteCollect")
    @CheckPermission({"1", "0"})
    public ResultAjax deleteCollect(@RequestBody HashMap<String, String> map) {
        String userId = map.get("userId");
        String productId = map.get("productId");

        // 获取 ListOperations 对象
        ListOperations<String, Product> listOperations = redisTemplate.opsForList();

        // 获取用户的所有收藏
        List<Product> collects = listOperations.range(userId, 0, -1);

        if (collects != null && !collects.isEmpty()) {
            for (Product collect : collects) {
                if (productId.equals(collect.getId())) {
                    // 找到匹配的元素，从列表中删除
                    listOperations.remove(userId, 1, collect); // 删除第一个匹配的元素
                    return ResultAjax.success().add("result", "删除成功");
                }
            }
        }

        return ResultAjax.success().add("result", "删除失败");
    }
}
